/**
 * 
 */
package com.ceolt.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author yejf
 * bean工厂
 */
public class BeanFactory {

	private static final String _PATH = "bean.properties";
	
	private static Properties props = new Properties();
	
	/*****
	 * 使用静态代码块来加载 bean.properties文件
	 */
	static {
		try (InputStream in = Thread.currentThread()
					.getContextClassLoader().getResourceAsStream(_PATH);) {
			if(in != null) {
				props.load(in);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	/******
	 * 根据 key 来获取value
	 * @param key
	 * @return
	 */
	public static String getValue(String key) {
		return props != null ? props.getProperty(key) : null;
	}
	
	/************
	 * 根据给定的bean名字来获取此Bean的实例
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		String beanClass = getValue(name);
		//通过反射来生成Bean的实例
		try {
			Class<?> c = Class.forName(beanClass);
			//返回
			return c.newInstance();
		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
//			e.printStackTrace();
			throw new RuntimeException("实例化bean失败："+beanClass, e);
		}
	}
}
